﻿namespace GreenIsomer.Data.Entities.Ddl {
	using System;
	using System.IO;

	public class Table : TableBase {

		private TableColumnCollection columns;
		private ForeignKeyCollection foreignKeys;

		public Table() {
			columns = new TableColumnCollection();
			foreignKeys = new ForeignKeyCollection();
		}

		public string Schema { get; set; }

		public TableColumnCollection Columns {
			get { return columns; }
		}

		public PrimaryKey PrimaryKey { get; set; }

		public ForeignKeyCollection ForeignKeys {
			get { return foreignKeys; }
		}

		public virtual void WriteCreateScript(DdlWriter writer) {
			if(SuppressDdlOutput) return;

			writer.SkipLine();

			writer.WriteScript("CREATE TABLE ");

			writer.WriteSchemaPrefix(Schema);

			writer.WriteName(Name);
			writer.WriteScript(" (");

			writer.Indent++;
			writer.StartNewLine();

			bool itemWriten = false;

			foreach(TableColumn column in columns) {

				if(itemWriten) {
					writer.RemoveSpace();
					writer.WriteScript(",");
				} else itemWriten = true;

				column.WriteScript(writer);
			}

			if(PrimaryKey != null) {
				if(itemWriten) {
					writer.RemoveSpace();
					writer.WriteScript(",");
				}
				PrimaryKey.WriteCreateScript(writer);
			}

			writer.Indent--;
			writer.StartNewLine();

			writer.WriteScript(");");

			foreach(Index index in Indexes)
				index.WriteCreateScript(writer, Name, Schema);
		}

		public virtual void WriteDropScript(DdlWriter writer) {

			writer.StartNewLine();

			writer.WriteScript("DROP TABLE");

			writer.AddSpace();
			writer.WriteSchemaPrefix(Schema);
			writer.WriteName(Name);

			writer.WriteScript(";");
		}

	}

}